import React, { Component } from 'react'
import { connect } from 'react-redux'
import { Card, Button, Table, Icon, Popconfirm } from 'antd'

import { createContainer } from 'utils/hoc'
import ContentBox from 'components/contentBox'
import StatusFlow from './com/statusFlow'
import InvoiceModal from './com/invoiceModal'
import ConsigneeModal from './com/consigneeModal'
import GoodsModal from './com/goodsModal'
import CostModal from './com/costModal'
import TrackingOrderModal from './com/trackingOrderModal'
import SendMessageModal from './com/sendMessageModal'
import CloseOrderModal from './com/closeOrderModal'
import RemarkOrderModal from './com/remarkOrderModal'
import DeliveredInfoModal from './com/deliveredInfoModal'
import LogisticsModal from './com/logisticsModal'
import RefundModal from './com/refundModal'
import RefundInfoModal from './com/refundInfoModal'
import OrderDeliveryModal from './com/orderDeliveryModal'
// import Filters from 'components/common/filters'
// import CustomTable from 'components/common/table'
import { ORDER_STATUS, ORDER_FROM, PAY_CHANNEL } from 'constants'
import PropTypes from 'prop-types'
import Style from './details.css'
import { getPriceFilter } from 'utils/utils'

/**
 * "orderStatus": "订单状态(
 * 0-待支付,
 * 10-待发货,
 * 20-待收货,
 * 30-已完成,
 * 40-待退货,
 * 41-退货中,
 * 42-退货成功,
 * 50-待退款,
 * 51-退款中,
 * 52-退款成功,
 * 98-取消交易,
 * 99-订单关闭)"
 * */
class details extends Component {
  static propTypes = {
    getOrderDetail: PropTypes.func,
    remarkOrder: PropTypes.func,
    closeOrder: PropTypes.func,
    sendMessage: PropTypes.func,
    logistics: PropTypes.func,
    changeInvoice: PropTypes.func,
    changeReceiveInfo: PropTypes.func,
    match: PropTypes.object,
    orderDetail: PropTypes.object,
    deliveredInfo: PropTypes.object,
    logisticsList: PropTypes.array,
    confirmchangeReceiveInfoLoading: PropTypes.bool,
    confirmInvoiceLoading: PropTypes.bool,
    confirmRefundLoading: PropTypes.bool,
    changeOrderCostInfo: PropTypes.func,
    orderDeliveredInfo: PropTypes.func,
    getLogisticsInfo: PropTypes.func,
    refund: PropTypes.func,
    orderDelivery: PropTypes.func,
    refuse: PropTypes.func,
    getRefundDetailInfo: PropTypes.func,
    refundDetailInfo: PropTypes.any,
    confirmRefundInfoLoading: PropTypes.bool
  }
  constructor (props) {
    super(props)
    this.state = {
      // expandedRowKeys: [],
      showInvoiceModal: false,
      showConsigneeModal: false,
      showGoodsModal: false,
      showCostModal: false,
      showTrackingModal: false,
      showSendMessageModal: false,
      showCloseOrderModal: false,
      showRemarkOrderModal: false,
      showDeliveredInfoModal: false,
      showLogisticsModal: false,
      showRefundModal: false,
      showOrderDeliveryModal: false,
      showRefundDetailModal: false,

      currentChildOrderNo: null,
      baseInfoColumn: [
        {
          title: '订单编号',
          dataIndex: 'orderNo',
          width: 227
        },
        {
          title: '发货单流水号',
          dataIndex: 'autoCompleteDay',
          width: 250

        },
        {
          title: '用户手机号',
          dataIndex: 'userMobile',
          width: 250
        },
        {
          title: '支付方式',
          dataIndex: 'payChannel',
          width: 250,
          render: record => PAY_CHANNEL[record]
        },
        {
          title: '订单来源',
          dataIndex: 'orderResource',
          width: 250,
          render: record => ORDER_FROM[record]
        },
        {
          title: '订单类型',
          dataIndex: 'orderType'

        }
      ],
      baseInfoCol: [
        // {
        //   title: '配送方式',
        //   dataIndex: '',
        //   width: 250
        // },
        // {
        //   title: '物流单号',
        //   dataIndex: '',
        //   width: 250
        // },
        {
          title: '自动确认收货时间',
          dataIndex: 'autoCompleteDay',
          width: 227

        },
        {
          title: '订单可得积分',
          dataIndex: 'obtainIntegration',
          width: 250

        },
        {
          title: '订单可得成长值',
          dataIndex: 'obtainGrowthValue',
          width: 250

        },
        {
          title: '活动信息',
          dataIndex: 'activityInfo'
        }
      ],
      invoiceCol: [
        {
          title: '发票类型',
          dataIndex: 'invoiceType',
          width: 227
        },
        {
          title: '发票抬头',
          dataIndex: 'invoiceTitle'
        },
        {
          title: '发票内容',
          dataIndex: 'content'
        },
        {
          title: '收票人信息',
          // dataIndex: '',
          key: 'mobile',
          render: record => {
            return [record.mobile, record.email].join('|')
          }
        }
      ],
      userInfoCol: [
        {
          title: '收货人',
          dataIndex: 'consigneeName'
        },
        {
          title: '手机号码',
          dataIndex: 'consigneeMobile'
        },
        {
          title: '邮政编码',
          dataIndex: 'zipCode'
        },
        {
          title: '收货地址',
          dataIndex: 'addressDetails'
        }
      ],
      operateLogCol: [
        {
          title: '操作者',
          dataIndex: 'operator'
        },
        {
          title: '操作时间',
          dataIndex: 'operateTime'
        },
        {
          title: '订单状态',
          dataIndex: 'orderStatus'
        },
        {
          title: '付款状态',
          dataIndex: 'payStatus'
        },
        {
          title: '发货状态',
          dataIndex: 'deliveryStatus'
        },
        {
          title: '备注',
          dataIndex: 'operatorRecord'
        }
      ]
    }
  }

  componentDidMount () {
    this.queryDetail()
  }

  queryDetail = () => {
    const { id } = this.props.match.params
    this.id = id
    this.props.getOrderDetail({
      orderId: id
    })
  }
  // handleCheckGoods = record => {
  //   const { expandedRowKeys } = this.state
  //   if (expandedRowKeys.length && expandedRowKeys[0] === record.index) {
  //     this.setState({
  //       expandedRowKeys: []
  //     })
  //   } else {
  //     this.setState({
  //       expandedRowKeys: [record.index]
  //     })
  //   }
  // }

  confirmInvoiceModal = async form => {
    const { changeInvoice, orderDetail: { orderId } } = this.props
    await changeInvoice({
      orderId,
      ...form
    })
    this.setState({ showInvoiceModal: false })
    this.queryDetail()
  }
  confirmConsigneeModal = async form => {
    const { changeReceiveInfo, orderDetail: { orderId } } = this.props
    await changeReceiveInfo({
      orderId,
      ...form
    })
    this.setState({ showConsigneeModal: false })
    this.queryDetail()
  }

  confirmGoodsModal = () => {
    console.log('details -> confirmGoodsModal -> confirmGoodsModal')
  }

  confirmCostModal = (form) => {
    const { orderDetail: { orderId }, changeOrderCostInfo } = this.props
    const { orderAmount } = form
    let temp = Math.floor(orderAmount * 100)
    changeOrderCostInfo({
      orderId,
      ...form,
      orderAmount: temp
    }).then(() => {
      this.setState({
        showCostModal: false
      })
      this.queryDetail()
    })
  }

  confirmTrackingOrderModal = () => {
  }

  confirmSendMessageModal = form => {
    const { orderDetail: { orderId }, sendMessage } = this.props
    sendMessage({
      orderId,
      ...form
    }).then(() => {
      this.setState({ showSendMessageModal: false })
      this.queryDetail()
    })
  }

  confirmCloseOrderModal = form => {
    const { orderDetail: { orderId }, closeOrder } = this.props
    closeOrder({ orderIds: [orderId], ...form }).then(() => {
      this.setState({ showCloseOrderModal: false })
      this.queryDetail()
    })
  }

  confirmRemarkOrderModal = form => {
    const { orderDetail: { orderId }, remarkOrder } = this.props
    remarkOrder({
      orderId,
      ...form
    }).then(() => {
      this.setState({ showRemarkOrderModal: false })
      this.queryDetail()
    })
  }

  confirmRefundMOdal = form => {
    const { currentChildOrderNo } = this.state
    const { refuse } = this.props
    refuse({
      // orderId,
      childOrderNo: currentChildOrderNo,
      auditOperate: 1,
      ...form
    }).then(() => {
      this.setState({ showRefundModal: false })
      this.queryDetail()
    })
  }

  // 部分发货
  confirmOrderDelivery = (form, cb) => {
    const { orderDetail: { orderId }, orderDelivery } = this.props
    orderDelivery({
      orderId,
      ...form
    }).then(() => {
      if (cb) {
        cb()
      }
      this.queryDetail()
    })
    console.log('form', form)
  }

  // 是否显示退款按钮
  isShowRefundButton = (orderStatus, childOrderStatus) => {
    // if (['10', '20', '30'].indexOf(childOrderStatus) > -1 && ['0', '98', '99'].indexOf(orderStatus) < 0) {
    if (orderStatus === '50' && childOrderStatus === '50') {
      return true
    }
    return false
  }

  getchildOrderCol = orderStatus => {
    return [
      {
        title: '商品图片',
        key: 'converImgUrl',
        render: record => (
          <img className={Style['goods-img']} src={record.converImgUrl || ''} alt='img' />
        )
      },
      {
        title: '商品名称',
        key: 'commodityName',
        render: ({ authorName, commodityName }) => {
          return (
            <>
              <span>{commodityName}</span><br />
              <span>{`创作者：${authorName}`}</span>
            </>
          )
        }
      },
      {
        title: '价格/货号',
        key: 'commodityNo',
        render: ({ commodityNo, commodityPrice }) => {
          return (
            <>
              <span>价格：¥{getPriceFilter(commodityPrice)}</span><br />
              <span>货号：{commodityNo}</span>
            </>
          )
        }
      },
      {
        title: '属性',
        dataIndex: 'commoditySpec'
      },
      {
        title: '数量',
        dataIndex: 'quantity'
      },
      {
        title: '小计',
        key: 'commodityPrice',
        render: ({ orderAmount }) => {
          return (
            <span>¥{getPriceFilter(orderAmount)}</span>
          )
        }
      },
      {
        title: '状态',
        dataIndex: 'orderStatus',
        render: orderStatus => `${ORDER_STATUS[orderStatus]}`
      },
      {
        title: '操作',
        render: record => {
          return (
            <>
              {record.orderStatus === '10' && <a className={Style['a-btn']} onClick={this.handleSendPartGoods}>发货</a>}
              {!!record.deliveredNo && <a className={Style['a-btn']} onClick={() => this.handleShowDeliveredInfoModal(record.deliveredNo)}>打印发货单</a>}
              {!!record.logisticsNo && <a className={Style['a-btn']} onClick={() => this.handleShowLogistics(record.logisticsNo)}>查看物流</a>}
              { /* TODO 退款信息 按钮出现条件 record.orderStatus === '52' && record.orderStatus === '10' && */ }
              {record.orderStatus === '52' && <a className={Style['a-btn']} onClick={() => this.handleShowRefundDetailModal(record.childOrderNo)}>退款信息</a>}
              {this.isShowRefundButton(orderStatus, record.orderStatus) && <a className={Style['a-btn']} onClick={() => this.handleRefund(record.childOrderNo)}>处理退款</a>}
              {this.isShowRefundButton(orderStatus, record.orderStatus) && <Popconfirm placement='top' title='是否拒绝退款' onConfirm={() => this.handleRefuse(record.childOrderNo)}><a className={Style['a-btn']}>拒绝退款</a></Popconfirm>}
            </>
          )
        }
      }
    ]
  }
  handleShowDeliveredInfoModal = deliveredNo => {
    this.setState({
      showDeliveredInfoModal: true
    })
    this.props.orderDeliveredInfo({ deliveredNo }).then(() => {

    })
  }

  handleShowLogistics = logisticsNo => {
    this.setState({
      showLogisticsModal: true
    })
    this.props.getLogisticsInfo({ logisticsNo })
  }

  handleShowRefundDetailModal = childOrderNo => {
    this.setState({
      showRefundDetailModal: true
    })
    // 获取退款详情
    this.props.getRefundDetailInfo({ childOrderNo })
  }

  handleRefund = childOrderNo => {
    this.setState({
      showRefundModal: true,
      currentChildOrderNo: childOrderNo
    })
  }

  handleRefuse = childOrderNo => {
    const { refuse } = this.props
    refuse({
      childOrderNo,
      returnCommodityFlag: 0,
      auditOperate: 2,
      remark: '拒绝退款'
    }).then(() => {
      this.queryDetail()
    })
  }

  getCostInfoCol = () => {
    return [
      {
        title: '商品合计',
        dataIndex: 'commodityPriceCount',
        render: n => `¥${getPriceFilter(n)}`
      },
      {
        title: '实际价格',
        key: 'payAmount',
        dataIndex: 'payAmount',
        render: n => `¥${getPriceFilter(n)}`
      },
      {
        title: '优惠',
        dataIndex: 'membersAmount',
        render: n => `¥${getPriceFilter(n)}`

      },
      {
        title: '优惠理由',
        dataIndex: 'preferentialReason'
      },
      {
        title: '退款金额',
        key: 'orderId',
        dataIndex: 'refundAmount',
        render: n => `¥${getPriceFilter(n)}`

      }
    ]
  }
  // 部分发货
  handleSendPartGoods = () => {
    this.setState({
      showOrderDeliveryModal: true
    })
  }

  handleCloseOrderDeliveryModal = () => {
    this.setState({ showOrderDeliveryModal: false })
    this.queryDetail()
  }

  ButtonWrap = () => {
    const { orderDetail } = this.props
    const { invoiceRes = {}, orderStatus } = orderDetail || {}
    const { invoiceFlag } = invoiceRes || {}
    // TODO 已开发票 按钮
    return (
      <div className={Style['btn-wrap']}>
        {!(invoiceFlag === 1) && <Button type='primary' onClick={() => this.setState({ showInvoiceModal: true })}>修改发票信息</Button>}
        {(orderStatus === '0' || orderStatus === '10') && <Button type='primary' onClick={() => this.setState({ showConsigneeModal: true })}>修改收货人信息</Button>}
        {(orderStatus === '0' || orderStatus === '10') && <Button type='primary' onClick={() => this.setState({ showGoodsModal: true })}>修改商品信息</Button>}
        {orderStatus === '0' && <Button type='primary' onClick={() => this.setState({ showCostModal: true })}>修改费用信息</Button>}
        {/* <Button type='primary' onClick={() => this.setState({ showTrackingModal: true })}>订单跟踪</Button> */}

        {/* <Button type='primary' onClick={() => this.setState({ showSendMessageModal: true })}>发送APP推送</Button> */}
        <Button type='primary' onClick={() => this.setState({ showCloseOrderModal: true })}>关闭订单</Button>
        <Button type='primary' onClick={() => this.setState({ showRemarkOrderModal: true })}>备注订单</Button>
      </div>
    )
  }

  render () {
    const {
      baseInfoColumn,
      baseInfoCol,
      invoiceCol,
      userInfoCol,
      operateLogCol,
      showInvoiceModal,
      showConsigneeModal,
      showGoodsModal,
      showCostModal,
      showTrackingModal,
      showSendMessageModal,
      showCloseOrderModal,
      showRemarkOrderModal,
      showDeliveredInfoModal,
      showLogisticsModal,
      showRefundModal,
      showOrderDeliveryModal,
      showRefundDetailModal
    } = this.state
    const { orderDetail, confirmchangeReceiveInfoLoading, confirmInvoiceLoading, confirmRefundLoading, deliveredInfo, logisticsList, confirmRefundInfoLoading } = this.props
    const { invoiceRes = [], childOrderList = [], operateLogList = [], ...reset } = orderDetail || {}
    const { orderStatus, createTime, payTime, deliveryTime, receiveTime } = reset
    let operateLogListWithKey = (operateLogList || []).map((n, i) => {
      return {
        key: i,
        ...n
      }
    })
    const list = [
      {
        name: '提交订单',
        time: createTime
      },
      {
        name: '支付订单',
        time: payTime
      },
      {
        name: '平台发货',
        time: deliveryTime
      },
      {
        name: '确认发货',
        time: receiveTime
      },
      {
        name: '完成评价',
        time: ''
      }
    ]

    return (
      <>
        <ContentBox>
          <div className={Style.details}>
            <StatusFlow list={list} />
            <div style={{ height: 20 }} />
            <Card
              title={(<div className={Style['cusotom-card-title']}>
                <Icon type='info-circle' />
                <span>当前订单状态:{ORDER_STATUS[orderStatus]}</span>
              </div>)}
              bordered
              headStyle={{ backgroundColor: '#FAFAFA', color: '#FF0000' }}
              extra={
                this.ButtonWrap()
              }
            >
              <div className={Style['wrap']}>
                <p className={Style['detail-title']}>基本信息</p>
                {/* {
                  orderStatus === '10' &&
                  <Button type='primary' onClick={this.handleSendPartGoods}>部分发货</Button>} */}
              </div>
              <Table rowKey='orderId' loading={!reset} columns={baseInfoColumn} pagination={false} dataSource={[reset]} />
              <Table rowKey='orderid' loading={!reset} columns={baseInfoCol} pagination={false} dataSource={[reset]} />
              <div style={{ height: 50 }} />
              <p className={Style['detail-title']}>发票信息</p>
              <Table rowKey='invoiceId' loading={!reset} columns={invoiceCol} pagination={false} dataSource={invoiceRes ? [invoiceRes] : []} />
              <div style={{ height: 50 }} />
              <p className={Style['detail-title']}>收货人信息</p>
              <Table rowKey='orderId' loading={!reset} columns={userInfoCol} pagination={false} dataSource={[reset]} />
              <div style={{ height: 50 }} />
              <p className={Style['detail-title']}>商品信息</p>
              <Table rowKey='childOrderNo' columns={this.getchildOrderCol(orderStatus)} pagination={false} dataSource={childOrderList} />
              <div style={{ height: 50 }} />
              <p className={Style['detail-title']}>费用信息</p>
              <Table rowKey='orderId' columns={this.getCostInfoCol()} pagination={false} dataSource={[reset]} />
              <div style={{ height: 50 }} />
              <p className={Style['detail-title']}>操作信息</p>
              <Table loading={!reset} columns={operateLogCol} pagination={false} dataSource={operateLogListWithKey} />
            </Card>
            <InvoiceModal
              visible={showInvoiceModal}
              confirmLoading={confirmInvoiceLoading}
              init={invoiceRes}
              onCancel={
                () => {
                  this.setState({ showInvoiceModal: false })
                }
              }
              onOk={this.confirmInvoiceModal}
            />
            <ConsigneeModal visible={showConsigneeModal} init={reset} confirmLoading={confirmchangeReceiveInfoLoading} onCancel={() => this.setState({ showConsigneeModal: false })} onOk={this.confirmConsigneeModal} />
            <GoodsModal visible={showGoodsModal} dataSource={childOrderList} onCancel={() => this.setState({ showGoodsModal: false }, () => { this.queryDetail() })} onOk={this.confirmGoodsModal} />
            <CostModal visible={showCostModal} init={[reset]} onCancel={() => this.setState({ showCostModal: false })} onOk={this.confirmCostModal} />
            <TrackingOrderModal visible={showTrackingModal} onCancel={() => this.setState({ showTrackingModal: false })} onOk={this.confirmTrackingOrderModal} />
            <SendMessageModal visible={showSendMessageModal} onCancel={() => this.setState({ showSendMessageModal: false })} onOk={this.confirmSendMessageModal} />
            <CloseOrderModal visible={showCloseOrderModal} onCancel={() => this.setState({ showCloseOrderModal: false })} onOk={this.confirmCloseOrderModal} />
            <RemarkOrderModal visible={showRemarkOrderModal} onCancel={() => this.setState({ showRemarkOrderModal: false })} onOk={this.confirmRemarkOrderModal} />
            <DeliveredInfoModal visible={showDeliveredInfoModal} onCancel={() => this.setState({ showDeliveredInfoModal: false })} deliveredInfo={deliveredInfo} />
            <LogisticsModal visible={showLogisticsModal} onCancel={() => this.setState({ showLogisticsModal: false })} logisticsList={logisticsList} />
            <RefundModal visible={showRefundModal} confirmLoading={confirmRefundLoading} onCancel={() => this.setState({ showRefundModal: false })} onOk={this.confirmRefundMOdal} />
            <RefundInfoModal visible={showRefundDetailModal} confirmLoading={confirmRefundInfoLoading} onCancel={() => this.setState({ showRefundDetailModal: false })} />
            <OrderDeliveryModal visible={showOrderDeliveryModal} onCancel={this.handleCloseOrderDeliveryModal} onOk={this.confirmOrderDelivery} childOrderList={childOrderList} handleShowDeliveredInfoModal={this.handleShowDeliveredInfoModal} />
          </div>
        </ContentBox>
      </>
    )
  }
}

const mapState = state => ({
  orderDetail: state.order.orderDetail,
  confirmchangeReceiveInfoLoading: state.loading.effects.order.changeReceiveInfo,
  confirmRefundInfoLoading: state.loading.effects.order.getRefundDetailInfo,
  confirmInvoiceLoading: state.loading.effects.order.changeInvoice,
  confirmRefundLoading: state.loading.effects.order.refund,
  logisticsList: state.order.logisticsList,
  deliveredInfo: state.order.deliveredInfo,
  refundDetailInfo: state.order.refundDetailInfo
})
const mapDispatch = dispatch => ({
  login: dispatch.common.createLogin,
  closeOrder: dispatch.order.closeOrder,
  logistics: dispatch.order.logistics,
  sendMessage: dispatch.order.sendMessage,
  getOrderDetail: dispatch.order.getOrderDetail,
  changeReceiveInfo: dispatch.order.changeReceiveInfo,
  remarkOrder: dispatch.order.remarkOrder,
  changeInvoice: dispatch.order.changeInvoice,
  changeOrderCostInfo: dispatch.order.changeOrderCostInfo,
  orderDeliveredInfo: dispatch.order.orderDeliveredInfo,
  getLogisticsInfo: dispatch.order.getLogisticsInfo,
  refund: dispatch.order.refund,
  orderDelivery: dispatch.order.orderDelivery,
  refuse: dispatch.order.refuse,
  getRefundDetailInfo: dispatch.order.getRefundDetailInfo
})

export default createContainer(
  connect(
    mapState,
    mapDispatch
  )(details)
)
